<template>

  <div class="app-container">

    <el-button type="text" @click="openChapterDialog()">添加章节</el-button>

    <!-- 章节 -->
    <el-collapse v-model="activeNames" class="chapter-collapse">
      <el-collapse-item 
        v-for="chapter in chapterVideoList" 
        :key="chapter.id" 
        :name="chapter.id"
        class="chapter-item">
        
        <template slot="title">
          <div class="chapter-header" style="display: flex; justify-content: space-between; align-items: center;">
            <span class="chapter-title">{{ chapter.title }}</span>
            <span class="chapter-actions" >
              <el-button type="text" @click.stop="openVideo(chapter.id)">添加小节</el-button>
              <el-button type="text" @click.stop="openEditChatper(chapter.id)">编辑</el-button>
              <el-button type="text" @click.stop="removeChapter(chapter.id)">删除</el-button>
            </span>
          </div>
        </template>

        <!-- 视频列表 -->
        <ul class="video-list">
          <li v-for="video in chapter.children" :key="video.id">
            <p style="display: flex; justify-content: space-between; align-items: center;">
              {{ video.title }}
              <span class="acts">
                <el-button type="text" @click.stop="openEditVideo(video.id)">编辑</el-button>
                <el-button type="text" @click.stop="removeVideo(video.id)">删除</el-button>
              </span>
            </p>
          </li>
        </ul>
      </el-collapse-item>
    </el-collapse>

    <!-- 添加表单 -->
    <el-dialog :visible.sync="dialogChapterFormVisible" title="添加章节">
        <el-form :model="chapter" label-width="120px">
            <el-form-item label="章节标题">
                <el-input v-model="chapter.title"/>
            </el-form-item>
            <el-form-item label="章节排序">
                <el-input-number v-model="chapter.sort" :min="0" controls-position="right"/>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogChapterFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveOrUpdate">确 定</el-button>
        </div>
    </el-dialog>

    <!-- 添加小节表单 -->
    <el-dialog :visible.sync="dialogVideoFormVisible" title="添加小节">
      <el-form :model="video" label-width="120px">
        <el-form-item label="小节标题">
          <el-input v-model="video.title"/>
        </el-form-item>
        <el-form-item label="小节排序">
          <el-input-number v-model="video.sort" :min="0" controls-position="right"/>
        </el-form-item>
        <el-form-item label="是否免费">
          <el-radio-group v-model="video.isFree">
            <el-radio :label="1">免费</el-radio>
            <el-radio :label="0">默认</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上传视频">
            <el-upload
                :on-success="handleVodUploadSuccess"
                :on-remove="handleVodRemove"
                :before-remove="beforeVodRemove"
                :on-exceed="handleUploadExceed"
                :file-list="fileList"
                :action="BASE_API+'/eduvod/video/uploadAlyiVideo'"
                :limit="1"
                class="upload-demo">
            <el-button size="small" type="primary">上传视频</el-button>
            <el-tooltip placement="right-end">
                <div slot="content">最大支持1G，<br>
                    支持3GP、ASF、AVI、DAT、DV、FLV、F4V、<br>
                    GIF、M2T、M4V、MJ2、MJPEG、MKV、MOV、MP4、<br>
                    MPE、MPG、MPEG、MTS、OGG、QT、RM、RMVB、<br>
                    SWF、TS、VOB、WMV、WEBM 等视频格式上传</div>
                <i class="el-icon-question"/>
            </el-tooltip>
            </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVideoFormVisible = false">取 消</el-button>
        <el-button :disabled="saveVideoBtnDisabled" type="primary" @click="saveOrUpdateVideo">确 定</el-button>
      </div>
    </el-dialog>

    <div class="bottom-actions">
      <el-button type="primary" @click="handleSave">保存</el-button>
      <el-button @click="handleCancel">取消</el-button>
    </div>

  </div>
</template>
<script>
import chapter from '@/api/edu/chapter'
import video from '@/api/edu/video'

export default {
    data() {
        return {
            activeNames: [],
            saveVideoBtnDisabled: false,
            courseId:'',//课程id
            chapterVideoList:[],
            tempChapterData: {}, // 临时存储章节修改
            tempVideoData: {},   // 临时存储小节修改
            chapter:{ //封装章节数据
                title: '',
                sort: 0
            },
            video: {
                title: '',
                sort: 0,
                isFree: 0,
                videoSourceId: '',
                chapterId: '',
                courseId: '',
                videoOriginalName:''//视频名称
            },
            dialogChapterFormVisible:false,//章节弹框
            dialogVideoFormVisible:false, //小节弹框
            fileList: [],//上传文件列表
            BASE_API: process.env.BASE_API // 接口API地址
            
        }
    },
    created() {
        //获取路由的id值
        if(this.$route.params && this.$route.params.id) {
            this.courseId = this.$route.params.id
            //根据课程id查询章节和小节
            this.getChapterVideo()
        }
    },
    methods:{
        toggleChapter(chapterId) {
            const index = this.activeNames.indexOf(chapterId)
            if (index > -1) {
                this.activeNames.splice(index, 1)
            } 
            else {
                this.activeNames.push(chapterId)
            }
        },
        //上传视频成功调用的方法
        handleVodUploadSuccess(response, file, fileList) {
            //上传视频id赋值
            this.video.videoSourceId = response.data.videoId
            //上传视频名称赋值
            this.video.videoOriginalName = file.name

            this.fileList = [{
                name: file.name,
                status: 'success'
            }]
        },
        handleUploadExceed() {
            this.$message.warning('想要重新上传视频，请先删除已上传的视频')
        },
        //点击确定调用的方法
        handleVodRemove() {
            //调用接口的删除视频的方法
            video.deleteAliyunvod(this.video.videoSourceId)
                .then(response => {
                    //提示信息
                    this.$message({
                        type: 'success',
                        message: '删除视频成功!'
                    });
                    //把文件列表清空
                    this.fileList = []
                    //把video视频id和视频名称值清空
                    //上传视频id赋值
                    this.video.videoSourceId = ''
                    //上传视频名称赋值
                    this.video.videoOriginalName = ''
                })
        },
        //点击×调用这个方法
        beforeVodRemove(file,fileList) {
            return this.$confirm(`确定移除 ${ file.name }？`)
        },

//==============================小节操作====================================
        //删除小节
        removeVideo(id) {
            this.$confirm('此操作将删除小节, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 如果是临时小节，直接从前端删除
                if(id.startsWith('temp_')) {
                    for (const chapter of this.chapterVideoList) {
                        if (chapter.children) {
                            const index = chapter.children.findIndex(v => v.id === id)
                            if(index !== -1) {
                                chapter.children.splice(index, 1)
                                return
                            }
                        }
                    }
                    this.$message.warning('未找到要删除的小节')
                    return
                }
                // 正式小节，调用API删除
                video.deleteVideo(id).then(response => {
                    if(response.code === 200) {
                        this.$message.success('删除小节成功!')
                        this.getChapterVideo()
                    } else {
                        this.$message.warning(response.message || '删除小节完成，但视频可能未删除')
                        this.getChapterVideo()
                    }
                })
                .catch(error => {
                    this.$message.error('删除失败')
                })
            }).catch(() => {
                this.$message.info('已取消删除')
            })
        },
        //添加小节弹框的方法
        openVideo(chapterId) {
            this.video = { // 重置表单
                 title: '',
                 sort: 0,
                 isFree: 0,
                 videoSourceId: '',
                 videoOriginalName: '',
                 chapterId: chapterId,
                 courseId: this.courseId
             }
             this.fileList = []
             //弹框
            this.dialogVideoFormVisible = true
        },
        //添加小节
        addVideo() {
            // 确保设置了所有必要字段
            const videoData = {
                title: this.video.title,
                sort: this.video.sort,
                isFree: this.video.isFree ? 1 : 0,
                videoSourceId: this.video.videoSourceId,
                videoOriginalName: this.video.videoOriginalName,
                chapterId: this.video.chapterId,
                courseId: this.courseId
            };
            // 验证必要字段
            if (!videoData.chapterId) {
                this.$message.error('请选择章节')
                return
            }
            video.addVideo(videoData).then(response => {
                this.dialogVideoFormVisible = false
                this.$message.success('添加小节成功!')
                this.getChapterVideo()
            })
            .catch(error => {
                this.$message.error('添加小节失败: ' + error.message)
            })
        },
        openEditVideo(videoId) {
             video.getVideo(videoId)
                .then(response => {
                    const videoData = response.data.video
                    this.video = {
                        ...videoData,
                        isFree: videoData.isFree ? 1 : 0
                    }
                    // 存储原始数据
                    this.tempVideoData[videoId] = {...videoData}
                    this.dialogVideoFormVisible = true
                    // 设置文件列表
                    if (videoData.videoOriginalName) {
                        this.fileList = [{
                            name: videoData.videoOriginalName,
                            status: 'success'
                        }]
                    } else {
                        this.fileList = []
                    }
                })
        },
        saveOrUpdateVideo() {
            const videoToSave = {
                ...this.video,
                isFree: this.video.isFree === 1
            }
            if(this.video.id) {
                let found = false
                for (const chapter of this.chapterVideoList) {
                    if (chapter.children) {
                        const index = chapter.children.findIndex(v => v.id === this.video.id)
                        if(index !== -1) {
                            this.$set(chapter.children, index, {
                                ...this.video
                            })
                            found = true
                            break
                        }
                    }
                }
                if (!found) {
                    const chapterIndex = this.chapterVideoList.findIndex(c => c.id === this.video.chapterId)
                    if(chapterIndex !== -1) {
                        if(!this.chapterVideoList[chapterIndex].children) {
                            this.$set(this.chapterVideoList[chapterIndex], 'children', [])
                        }
                        this.chapterVideoList[chapterIndex].children.push({
                            ...this.video
                        })
                    }
                }
            
            } else{
                const chapterIndex = this.chapterVideoList.findIndex(c => c.id === this.video.chapterId)
                if(chapterIndex !== -1) {
                    const newVideo = {
                        id: 'temp_' + Date.now(),
                        ...this.video
                    }
                    if(!this.chapterVideoList[chapterIndex].children) {
                        this.$set(this.chapterVideoList[chapterIndex], 'children', [])
                    }
                    this.chapterVideoList[chapterIndex].children.push(newVideo)
                }
            }
            this.dialogVideoFormVisible = false
            this.$message.success('修改已暂存，请点击保存按钮提交')
        },
        updateVideo() {
            video.updateVideo(this.video)
                 .then(response => {
                    this.dialogVideoFormVisible = false
                    this.$message({
                        type: 'success',
                        message: '修改小节成功!'
                    });
                this.getChapterVideo()
                this.video = {} // 清空表单数据
                })
        },

//==============================章节操作====================================
        //删除章节
        removeChapter(chapterId) {
            this.$confirm('此操作将删除章节, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {  //点击确定，执行then方法
                //调用删除的方法
                chapter.deleteChapter(chapterId)
                    .then(response =>{//删除成功
                    //提示信息
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    //刷新页面
                    this.getChapterVideo()
                })
            }) //点击取消，执行catch方法
        },
        //修改章节弹框数据回显
        openEditChatper(chapterId) {
           chapter.getChapter(chapterId).then(response => {
                this.chapter = {...response.data.chapter}
                // 存储原始数据
                this.tempChapterData[chapterId] = {...response.data.chapter}
                this.dialogChapterFormVisible = true
           })

        },
        //弹出添加章节页面
        openChapterDialog() {
            //弹框
            this.dialogChapterFormVisible = true
            //表单数据清空
            this.chapter.title = ''
            this.chapter.sort = 0
        },
        //添加章节
        addChapter() {
            //设置课程id到chapter对象里面
            this.chapter.courseId = this.courseId
            chapter.addChapter(this.chapter)
                .then(response => {
                    //关闭弹框
                    this.dialogChapterFormVisible = false
                    //提示
                    this.$message({
                        type: 'success',
                        message: '添加章节成功!'
                    });
                    //刷新页面
                    this.getChapterVideo()
                })
        },
        //修改章节的方法
        updateChapter() {
            chapter.updateChapter(this.chapter)
                .then(response =>  {
                    //关闭弹框
                    this.dialogChapterFormVisible = false
                    //提示
                    this.$message({
                        type: 'success',
                        message: '修改章节成功!'
                    });
                    //刷新页面
                    this.getChapterVideo()
                })
        },
        saveOrUpdate() {
            if(!this.chapter.id) {
                const newChapter = {
                    id: 'temp_' + Date.now(),
                    ...this.chapter,
                    children: []
                }
                this.chapterVideoList.push(newChapter)
            } else {
                const index = this.chapterVideoList.findIndex(c => c.id === this.chapter.id)
                if (index !== -1) {
                    this.chapterVideoList.splice(index, 1, {
                        ...this.chapterVideoList[index],
                        ...this.chapter
                    })
                }
            }
            this.dialogChapterFormVisible = false
            this.$message.success('修改已暂存，请点击保存按钮提交')
        },
        //根据课程id查询章节和小节
        getChapterVideo() {
            chapter.getAllChapterVideo(this.courseId)
                .then(response => {
                    this.chapterVideoList = response.data.allChapterVideo
                    // 初始化临时存储
                    this.tempChapterData = {}
                    this.tempVideoData = {}
                    this.chapterVideoList.forEach(chapterItem => {
                        this.tempChapterData[chapterItem.id] = {...chapterItem}
                        if (chapterItem.children) {
                            chapterItem.children.forEach(videoItem => {
                                this.tempVideoData[videoItem.id] = {...videoItem}
                            })
                        }
                    })
                })
        },
        handleSave() {
            this.$confirm('确定要保存所有修改吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const promises = []
                // 1. 处理章节修改
                this.chapterVideoList.forEach(chapterItem => {
                    if (chapterItem.id.startsWith('temp_')) {
                        // 新增章节
                        promises.push(
                            chapter.addChapter({
                                title: chapterItem.title,
                                sort: chapterItem.sort,
                                courseId: this.courseId
                            })
                        )
                    }else {
                        // 检查章节是否有修改
                        if(this.tempChapterData[chapterItem.id] && (chapterItem.title !== this.tempChapterData[chapterItem.id].title || chapterItem.sort !== this.tempChapterData[chapterItem.id].sort)){
                            // 更新章节
                            promises.push(chapter.updateChapter({
                                id: chapterItem.id,
                                title: chapterItem.title,
                                sort: chapterItem.sort
                            }))
                        }
                    }
                    // 处理小节修改
                    if (chapterItem.children) {
                        chapterItem.children.forEach(videoItem => {
                            if (videoItem.id.startsWith('temp_')){
                                // 新增小节
                                promises.push(video.addVideo({
                                    title: videoItem.title,
                                    sort: videoItem.sort,
                                    isFree: videoItem.free ? 1 : 0,
                                    videoSourceId: videoItem.videoSourceId,
                                    chapterId: chapterItem.id,
                                    courseId: this.courseId,
                                    videoOriginalName: videoItem.videoOriginalName
                                }))
                            } else{
                                // 检查小节是否有修改
                                if (this.tempVideoData[videoItem.id] && (videoItem.title !== this.tempVideoData[videoItem.id].title || videoItem.sort !== this.tempVideoData[videoItem.id].sort || videoItem.free !== this.tempVideoData[videoItem.id].free || videoItem.videoSourceId !== this.tempVideoData[videoItem.id].videoSourceId)){
                                    // 更新小节
                                    promises.push(video.updateVideo({
                                        id: videoItem.id,
                                        title: videoItem.title,
                                        sort: videoItem.sort,
                                        free: videoItem.free,
                                        videoSourceId: videoItem.videoSourceId,
                                        videoOriginalName: videoItem.videoOriginalName
                                    }))
                                }
                            }
                        })
                    }
                })
                // 执行保存
                if (promises.length > 0) {
                    Promise.all(promises).then(() => {
                        this.$message.success('所有修改已保存')
                        this.$router.push('/course/list')
                    })
                    .catch(error => {
                        this.$message.error('保存失败: ' + error.message)
                        this.getChapterVideo()
                    })
                } else {
                    this.$router.push('/course/list')
                }
            }).catch(() => {
                this.$message.info('已取消保存');
            })
        },
        handleCancel() {
            this.$confirm('确定要取消所有修改吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.getChapterVideo()
                this.$message.info('已放弃所有修改')
                this.$router.push('/course/list')
            }).catch(() => {
                this.$message.info('已取消操作')        
            })
        }
        
    }
}
</script>

<style scoped>
.bottom-actions {
  margin-top: 20px;
  padding: 20px 0;
  text-align: center;
  border-top: 1px solid #eee;
}

.bottom-actions .el-button {
  margin: 0 10px;
  min-width: 100px;
}
</style>